<script lang="ts" setup name="LoginForm">
import { ref } from 'vue'
import useStore from '@/store'
import { useRouter, useRoute } from 'vue-router'
// (1) 导入，vee-validate实现一种通用的表单校验
import { useField, useForm } from 'vee-validate'
import { useCountDown } from '@/utils/hooks';
// 导入校验工具函数
import {
    accountRule,
    passwordRule,
    isAgreeRule,
    mobileRule,
    codeRule
} from '@/utils/validate'
import Message from '@/components/XtxMessage';
const { user, cart } = useStore()
const router = useRouter()
const route = useRoute()

// (2) 传入规则调用 useForm方法，传入参数
const { validate, resetForm } = useForm({
    // 表单初始值，可以设置默认值
    initialValues: {
        account: 'xiaotuxian001', // 账号
        password: '123456', // 密码
        isAgree: true, // 是否勾选了 服务条框
        mobile: '13666666666', // 手机号
        code: '123456', // 验证码
        // account: '', // 账号
        // password: '', // 密码
        // isAgree: false, // 是否勾选了 服务条框
        // mobile: '', // 手机号
        // code: '', // 验证码
    },
    validationSchema: {
        // 账号校验规则
        account: accountRule,

        // 密码校验规则
        password: passwordRule,

        // 是否同意校验条款校验
        isAgree: isAgreeRule,

        // 手机号校验规则
        mobile: mobileRule,

        // 验证码校验规则
        code: codeRule,
    }
})

// (3) 使用
// 账号
const { value: account, errorMessage: accountErr } = useField<string>('account')
// 密码
const { value: password, errorMessage: passwordErr } = useField<string>('password')
// 是否同意
const { value: isAgree, errorMessage: isAgreeErr } = useField<boolean>('isAgree')
// 手机号登录
const { value: mobile, errorMessage: mobileErr, validate: mobileValidate } = useField<string>('mobile')
// 验证码
const { value: code, errorMessage: codeErr } = useField<string>('code')

// account: 账号登录 mobile: 短信登录
type LoginType = 'account' | 'mobile'
const type = ref<LoginType>('account')


// 点了登录
const hLogin = async () => {
    // 取出校验结果
    const res = await validate()
    // 调用登录函数
    try {
        if (type.value === 'account') {
            // 账号密码登录
            if (res.errors.account || res.errors.password || res.errors.isAgree) return // 账号登录校验未通过
            // 校验通过
            await user.login({
                account: account.value,
                password: password.value
            })
        } else {
            // 手机验证码登录
            if (res.errors.mobile || res.errors.mobile || res.errors.isAgree) return // 手机验证码登录校验未通过
            // 校验通过
            await user.mobileLogin(mobile.value, code.value)
        }
        // 合并未登录的购物车到线上
        cart.mergeLocalCart()
        Message.success('恭喜您, 登录成功!')
        const redirectUrl = (route.query.redirectUrl as string) || '/'
        router.push(redirectUrl)
    } catch (err) {
        console.log(err)
    }

}

// 登录方式切换
const changeType = (newType: LoginType) => {
    type.value = newType
    // 重置表单
    resetForm()
}


// 获取手机号表单的dom
const refMobile = ref<null | HTMLInputElement>(null)

// 定时器函数
const { time, start } = useCountDown()


// 点了发送验证码
const send = async () => {
    // 当倒计时的时候, 无法点击再次获取验证码
    if (time.value > 0) return // 不让用户一直点击
    // 手机号校验,// 单独解构出的手机号校验
    const res = await mobileValidate()
    // ? 表示可选链，有就调用他的方法
    if (!res.valid) return refMobile.value?.focus() // 验证未通过，获取焦点
    // 验证通过
    try {
        await user.sendMobileMsg(mobile.value)
        Message.success('发送验证码成功！')
        // 开启倒计时
        start()
    } catch (err) {

    }
}
</script>
<template>
    <div class="account-box">
        <div class="toggle">
            <a @click="changeType('account')" href="javascript:;" v-if="type === 'mobile'">
                <i class="iconfont icon-user"></i> 使用账号登录
            </a>
            <a @click="changeType('mobile')" href="javascript:;" v-else>
                <i class="iconfont icon-msg"></i> 使用短信登录
            </a>
        </div>
        <div class="form">
            <template v-if="type === 'account'">
                <div class="form-item">
                    <div class="input">
                        <i class="iconfont icon-user"></i>
                        <input v-model="account" type="text" placeholder="请输入用户名或手机号" />
                    </div>
                    <!-- 账号验证未通过显示 -->
                    <div class="error" v-if="accountErr">
                        <i class="iconfont icon-warning" />{{ accountErr }}
                    </div>
                </div>
                <div class="form-item">
                    <div class="input">
                        <i class="iconfont icon-lock"></i>
                        <input v-model="password" type="password" placeholder="请输入密码" />
                    </div>
                    <!-- 密码验证未通过显示 -->
                    <div class="error" v-if="passwordErr">
                        <i class="iconfont icon-warning" />{{ passwordErr }}
                    </div>
                </div>
            </template>
            <template v-else>
                <div class="form-item">
                    <div class="input">
                        <i class="iconfont icon-user"></i>
                        <input ref="refMobile" v-model="mobile" type="text" placeholder="请输入手机号" />
                    </div>
                    <!-- 手机号验证未通过显示 -->
                    <div class="error" v-if="mobileErr">
                        <i class="iconfont icon-warning" />{{ mobileErr }}
                    </div>
                </div>
                <div class="form-item">
                    <div class="input">
                        <i class="iconfont icon-code"></i>
                        <input v-model="code" type="password" placeholder="请输入验证码" />
                        <span @click="send" class="code">
                            {{ time === 0 ? '发送验证码' : `${time}s后发送` }}
                        </span>
                    </div>
                    <!-- 验证码未通过显示 -->
                    <div class="error" v-if="codeErr">
                        <i class="iconfont icon-warning" />{{ codeErr }}
                    </div>
                </div>
            </template>
            <div class="form-item">
                <div class="agree">
                    <!-- 复选框组件 -->
                    <XtxCheckbox v-model="isAgree">我已同意</XtxCheckbox>
                    <a href="javascript:;">《隐私条款》</a>
                    <span>和</span>
                    <a href="javascript:;">《服务条款》</a>
                </div>
                <!-- 验证未通过显示 -->
                <div class="error" v-if="isAgreeErr">
                    <i class="iconfont icon-warning" />{{ isAgreeErr }}
                </div>
            </div>
            <a @click="hLogin" href="javascript:;" class="btn">登录</a>
        </div>
        <div class="action">
            <a
                href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&amp;response_type=token&amp;scope=all&amp;redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
                <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="QQ登录"
                    border="0" />
            </a>
            <div class="url">
                <a href="javascript:;">忘记密码</a>
                <a href="javascript:;">免费注册</a>
            </div>
        </div>
    </div>
</template>

<style scoped lang="less">
// 账号容器
.account-box {
    .toggle {
        padding: 15px 40px;
        text-align: right;

        a {
            color: @xtxColor;

            i {
                font-size: 14px;
            }
        }
    }

    .form {
        padding: 0 40px;

        &-item {
            margin-bottom: 28px;

            .input {
                position: relative;
                height: 36px;

                >i {
                    width: 34px;
                    height: 34px;
                    background: #cfcdcd;
                    color: #fff;
                    position: absolute;
                    left: 1px;
                    top: 1px;
                    text-align: center;
                    line-height: 34px;
                    font-size: 18px;
                }

                input {
                    padding-left: 44px;
                    border: 1px solid #cfcdcd;
                    height: 36px;
                    line-height: 36px;
                    width: 100%;

                    &.error {
                        border-color: @priceColor;
                    }

                    &.active,
                    &:focus {
                        border-color: @xtxColor;
                    }
                }

                .code {
                    position: absolute;
                    right: 1px;
                    top: 1px;
                    text-align: center;
                    line-height: 34px;
                    font-size: 14px;
                    background: #f5f5f5;
                    color: #666;
                    width: 90px;
                    height: 34px;
                    cursor: pointer;
                }
            }

            >.error {
                position: absolute;
                font-size: 12px;
                line-height: 28px;
                color: @priceColor;

                i {
                    font-size: 14px;
                    margin-right: 2px;
                }
            }
        }

        .agree {
            a {
                color: #069;
            }
        }

        .btn {
            display: block;
            width: 100%;
            height: 40px;
            color: #fff;
            text-align: center;
            line-height: 40px;
            background: @xtxColor;

            &.disabled {
                background: #cfcdcd;
            }
        }
    }

    .action {
        padding: 20px 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        img {
            cursor: pointer;
        }

        .url {
            a {
                color: #999;
                margin-left: 10px;
            }
        }
    }
}
</style>